#include "RelOp.h"

void WriteOut::Run(Pipe &inPipe, FILE *outFile, Schema &mySchema){

    in = &inPipe;
    out = outFile;
    schema = &mySchema;

    pthread_create(&thread, NULL, WriteOutWorker, (void*)this);
}

void WriteOut::WaitUntilDone (){
    pthread_join(thread, NULL);
}

void WriteOut::Use_n_Pages(int n){
    nOfPages = n;
}

void WriteOut::DoWork(){
    int n = schema->GetNumAtts();
	Attribute *atts = schema->GetAtts();

    Record r;
    while(in->Remove(&r)){
        // loop through all of the attributes
        for (int i = 0; i < n; i++) {
            // print the attribute name
            fprintf(out, "%s: ", atts[i].name);

            // use the i^th slot at the head of the record to get the
            // offset to the correct attribute in the record
            int pointer = ((int *) r.bits)[i + 1];

            // here we determine the type, which given in the schema;
            // depending on the type we then print out the contents
            fprintf(out, "[");

            // first is integer
            if (atts[i].myType == Int) {
                int *myInt = (int *) &(r.bits[pointer]);
                fprintf(out, "%d", *myInt);

            // then is a double
            } else if (atts[i].myType == Double) {
                double *myDouble = (double *) &(r.bits[pointer]);
                fprintf(out, "%f", *myDouble);

            // then is a character string
            } else if (atts[i].myType == String) {
                char *myString = (char *) &(r.bits[pointer]);
                fprintf(out, "%s", myString);
            }

            fprintf(out, "]");

            // print out a comma as needed to make things pretty
            if (i != n - 1) {
                fprintf(out, ", ");
            }
        }

        fprintf(out, "\n");
    }
}

void *WriteOutWorker(void *param){
     WriteOut writeOut = *((WriteOut*) param);
     writeOut.DoWork();
}
